<template>
  <div class="wrap">
    <div>
      <label class="label-style">{{ $t('message.SoundInsulationWeightTool.type') }}：</label>
      <el-select size="small" v-model="frameType">
        <el-option :key="0" :label="$t('message.SoundInsulationWeightTool.fieldBlanket')" :value="0"/>
        <el-option :key="1" :label="$t('message.SoundInsulationWeightTool.frameBlanket')" :value="1"/>
      </el-select>
      <el-select size="small" v-model="splitLineType">
        <el-option :key="0" :label="$t('message.SoundInsulationWeightTool.splitLine')" :value="0"/>
        <el-option :key="1" :label="$t('message.SoundInsulationWeightTool.noSplitLine')" :value="1"/>
      </el-select>
      <el-button type="primary" size="small"
                 @click="calculateWeight">{{ $t('message.SoundInsulationWeightTool.compute') }}
      </el-button>
    </div>
    <div>
      <show-table :datum="datum"
                  :showTab="false"
                  :enable-freeze="false"
                  :editable="true"
                  height="350px"
                  ref="showTable"
                  :alias-col-name="variableFiledNames"
                  selected-mode="cell"
                  :ban-editor-col-name="banEditorColName"
                  :excel-import="true"
                  header-align="center"
                  :showOperationBtn="false"
                  cell-width="140px"
                  :value-change-callback="valueChangeCallback"
                  :defaultTableHead="defaultTableHead"
                  :permitTableDataEmpty="true">
<!--        :ban-editor-row="banEditorRow"     :fill-mode="true"-->
      </show-table>
    </div>
    <div class="label-container">
      <p><b>总重量：{{ this.totalWeight }}</b></p>
    </div>
    <div class="btn">
      <el-button type="primary"
                 size="small"
                 :disabled="componentState"
                 @click="exportData">{{ $t('message.SoundInsulationWeightTool.export') }}
      </el-button>
      <el-button size="small"
                 @click="cancel">{{ $t('message.SoundInsulationWeightTool.close') }}
      </el-button>
    </div>
  </div>
</template>

<script>
  import {soundInsulationWeightCommand} from "../../../command/SoundInsulationWeightCommand";
  import DialogMixin from "../DialogMixin";
  import * as XLSX from "xlsx";
  import saveAs from 'file-saver';

  export default {
    mixins: [DialogMixin],
    name: "CmdDlgSoundInsulationWeight",
    data() {
      return {
        frameType: 0,//框间：0， 框上：1
        splitLineType: 0,
        datum: [],
        variableFiledNames: {
          name: "零件名称",
          glasswoolLayer: "玻璃纤维棉\n层数",
          glasswoolDensity: "玻璃纤维棉\n密度(g/m²)",
          glasswoolArea: "玻璃纤维棉\n面积(m²)",
          glasswoolWeight: "玻璃纤维棉\n重量(g)",
          firebLayer: "耐火焰蔓延包覆层\n层数",
          firebDensity: "耐火焰蔓延包覆层\n密度(g/m²)",
          firebArea: "耐火焰蔓延包覆层\n面积(m²)",
          firebWeight: "耐火焰蔓延包覆层\n重量(g)",
          foilDensity: "箔\n密度(g/m²)",
          foilArea: "箔\n面积(m²)",
          foilWeight: "箔\n重量(g)",
          tapeLength: "胶带\n长度(m)",
          tapePerMeterWeight: "胶带\n每米的重量(g/m)",
          tapeWeight: "胶带\n重量(g)",
          hookLength: "挂钩\n长度(m)",
          hookPerMeterWeight: "挂钩\n每米的重量(g/m)",
          hookWeight: "挂钩\n重量(g)",
          loopLength: "环\n长度(m)",
          loopPerMeterWeight: "环\n每米的重量(g/m)",
          loopWeight: "环\n重量(g)",
          labelWeight: "标签\n重量(g)",
          totalWeight: "零件\n重量(g)"
        },
        banEditorColName: [
          "partname",
          "glasswoolLayer", "glasswoolDensity", "glasswoolArea", "glasswoolWeight",
          "firebLayer", "firebDensity", "firebArea", "firebWeight",
          "foilDensity", "foilArea", "foilWeight",
          "tapePerMeterWeight", "tapeWeight",
          "hookPerMeterWeight", "hookWeight",
          "loopPerMeterWeight", "loopWeight",
          "totalWeight"
        ],//设置不能编辑的列
        // banEditorRow: [0, 1, 2],//设置不能编辑的行
        variables: [],
        materials: [],
        totalWeight: 0,
        componentState: true,
        defaultTableHead: [],
      }
    },
    methods: {
      changePluginContainerHeight() {
        soundInsulationWeightCommand.changePluginContainerHeight({
          minWidth: this.$el.clientWidth, maxHeight: this.$el.clientHeight, width: 715,
        });
      },
      exportData() {
        let data = [];
        data.push(Object.values(this.variableFiledNames));
        this.datum.forEach(item => {
          data.push(Object.values(item));
        });
        let totalW = "总重量：" + this.totalWeight;
        data.push(["", "", "","","", "", "","","", "", "","","", "", "","","", "", "","","","", totalW]);
        if (data?.length > 0) {
          let workSheet = XLSX.utils.aoa_to_sheet(data);
          //遍历单元格并设置自动换行
          // for (let row in workSheet) {
          //   if (workSheet.hasOwnProperty(row) && typeof workSheet[row] === 'object') {
          //     for (let col in workSheet[row]) {
          //       if (workSheet[row]) {
          //         if (workSheet[row].hasOwnProperty(col)) {
          //           const cell = workSheet[row][col];
          //           cell.s = cell?.s || {};
          //           cell.s.alignment = cell.s.alignment || {};
          //           cell.s.alignment.wrapText = true;
          //         }
          //       }
          //     }
          //   }
          // }
          let workBook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workBook, workSheet, "隔热隔声重量统计");
          let excelBuffer = XLSX.write(workBook, {bookType: 'xlsx', type: 'array'});
          let dataBlob = new Blob([excelBuffer], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'});
          saveAs(dataBlob, '隔热隔声重量统计表.xlsx');
        } else {
          soundInsulationWeightCommand.eventBusAlertMsg("无隔热隔声重量统计数据，无法导出数据文件", "waring");
        }
      },
      cancel() {
        soundInsulationWeightCommand.closeActiveCmd();
      },
      calculateWeight() {
        this.datum.splice(0);
        this.totalWeight = 0;
        this.componentState = true;
        soundInsulationWeightCommand.getPartInfo().then(data => {
          for (let i = 0; i < data.length; i++) {
            this.addToList(data[i]);
          }
          if (this.datum.length > 0) {
            this.componentState = false;
          }
        });
      },
      addToList(data) {
        let variables = data.variables;
        let materials = data.materials;
        if (variables?.length === 0 || materials?.length === 0) {
          return;
        }
        //获取变量值
        let L1 = variables["L1"] ? variables["L1"] : 0;
        let L3 = variables["L3"] ? variables["L3"] : 0;
        let W1 = variables["W1"] ? variables["W1"] : 0;
        let A1 = variables["A1"] ? variables["A1"] : 0;
        let A2 = variables["A2"] ? variables["A2"] : 0;
        //面积转换成m2
        A1 = A1 / 1000000;
        A2 = A2 / 1000000;

        let glasswools = materials.filter(material => material.name.includes("玻璃"));
        let firebs = materials.filter(material => material.name.includes("耐火"));
        let foils = materials.filter(material => material.name.includes("foil"));
        let glasswool, fireb, foil;
        let G1=0, G2=0, G3=0, G4=0, G5=0, G6=0, G7=0;
        let totalWeight = 0;
        //玻璃纤维棉
        if (glasswools?.length > 0) {
          glasswool = glasswools[0];
        }
        if (glasswool) {
          let S_glass = (W1 * L1) / 1000000;
          let density = this.extractDecimalPart(glasswool.density);
          if (density) {
            G1 = (S_glass - A1) * glasswool.layer * density;
          }
          glasswool.density = density;
          S_glass = this.cutFloat(S_glass);
          G1 = this.cutFloat(G1);
          glasswool.area = S_glass;
          glasswool.weight = G1;
          totalWeight += G1;
        }
        //耐火焰蔓延包覆层
        if (firebs?.length > 0) {
          fireb = firebs[0];
          let S_fb = 0;
          if (this.splitLineType === 0) {
            if (this.frameType === 0) {
              S_fb = (L3 + 25.4 + 15 + fireb.layer * 10) * (W1 + 50.8 + 50.8 + 2 * fireb.layer * 10);
            } else {
              S_fb = (L3 + 25.4 + 15 + fireb.layer * 10) * (W1 + 25.4 + 25.4 + 2 * fireb.layer * 10);
            }
          } else {
            if (this.frameType === 0) {
              S_fb = (L3 + 25.4 + 25.4 + 2 * fireb.layer * 10) * (W1 + 50.8 + 50.8 + 2 * fireb.layer * 10);
            } else {
              S_fb = (L3 + 25.4 + 25.4 + 2 * fireb.layer * 10) * (W1 + 25.4 + 25.4 + 2 * fireb.layer * 10);
            }
          }
          S_fb = S_fb / 1000000;
          S_fb = this.cutFloat(S_fb);
          let density = this.extractDecimalPart(fireb.density);
          if (density) {
            G2 = S_fb * density;
            G2 = this.cutFloat(G2);
            fireb.density = density;
          }
          fireb.area = S_fb;
          fireb.weight = G2;
          totalWeight += G2;
        }
        //foil
        if (foils?.length > 0) {
          foil = foils[0];
          let layer = 2;
          let S_foil = 0;
          if (this.frameType === 0) {
            S_foil = (L1 + 25.4 * 2 + layer * 10) * (W1 + 50.8 * 2 + layer * 10);
          } else {
            S_foil = (L1 + 25.4 * 2 + layer * 10) * (W1 + 25.4 * 2 + layer * 10);
          }
          S_foil = S_foil / 1000000;
          S_foil = this.cutFloat(S_foil);
          let density = this.extractDecimalPart(foil.density);
          if (density) {
            G3 = (S_foil - A2) * 2 * density;
            G3 = this.cutFloat(G3);
            foil.density = density;
          }
          foil.area = S_foil;
          foil.weight = G3;
          totalWeight += G3;
        }
        //Tape
        let tapeLen = 5;
        G4 = this.computeTapeWeight(tapeLen);
        G4 = this.cutFloat(G4);
        totalWeight += G4;
        //Hook
        let hookLen = 10;
        G5 = this.computeHookWeight(hookLen);
        G5 = this.cutFloat(G5);
        totalWeight += G5;
        //Loop
        let loopLen = 10;
        G6 = this.computeLoopWeight(loopLen);
        G6 = this.cutFloat(G6);
        totalWeight += G6;
        //Label
        G7 = 1;
        totalWeight += G7;
        totalWeight = this.cutFloat(totalWeight);
        this.totalWeight += totalWeight;
        this.totalWeight = this.cutFloat(this.totalWeight);

        this.datum.push({
          name: data.name,
          glasswoolLayer: glasswool?.layer,
          glasswoolDensity: glasswool?.density,
          glasswoolArea: glasswool?.area,
          glasswoolWeight: glasswool?.weight,
          firebLayer: fireb?.layer,
          firebDensity: fireb?.density,
          firebArea: fireb?.area,
          firebWeight: fireb?.weight,
          foilDensity: foil?.density,
          foilArea: foil?.area,
          foilWeight: foil?.weight,
          tapeLength: tapeLen,
          tapePerMeterWeight: 6,
          tapeWeight: G4,
          hookLength: hookLen,
          hookPerMeterWeight: 18,
          hookWeight: G5,
          loopLength: loopLen,
          loopPerMeterWeight: 18,
          loopWeight: G6,
          labelWeight: G7,
          totalWeight: totalWeight
        });
      },
      
      cutFloat(value) {
        return Math.round(parseFloat(value) * 100) / 100.0;
      },

      computeTapeWeight(length) {
        return length * 6;
      },

      computeHookWeight(length) {
        return length * 18;
      },

      computeLoopWeight(length) {
        return length * 18;
      },

      extractDecimalPart(str) {
        let match = str.match(/^\d*(\.\d+)/);
        if (!match) {
          match = str.match(/^\d*/);
        }
        if (match) {
          return match[0];
        }
        return null;
      },

      valueChangeCallback(index, key, cellOldValue, cellNewValue) {
        let nLength = this.datum.length;
        if (index < nLength) {
          let modifyItem = this.datum[index];
          if (key.includes("tape")) {
            let oldWeight = this.cutFloat(modifyItem["tapeWeight"]);
            let weight = this.computeTapeWeight(this.cutFloat(cellNewValue));
            modifyItem["tapeWeight"] = weight;
            let weightDiff = this.cutFloat(weight) - oldWeight;
            this.totalWeight += weightDiff;
            modifyItem["totalWeight"] += weightDiff;
          } else if (key.includes("loop")) {
            let oldWeight = this.cutFloat(modifyItem["loopWeight"]);
            let weight = this.computeLoopWeight(this.cutFloat(cellNewValue));
            modifyItem["loopWeight"] = weight;
            let weightDiff = this.cutFloat(weight) - oldWeight;
            this.totalWeight += weightDiff;
            modifyItem["totalWeight"] += weightDiff;
          } else if (key.includes("hook")) {
            let oldWeight = this.cutFloat(modifyItem["hookWeight"]);
            let weight = this.computeHookWeight(this.cutFloat(cellNewValue));
            modifyItem["hookWeight"] = weight;
            let weightDiff = this.cutFloat(weight) - oldWeight;
            this.totalWeight += weightDiff;
            modifyItem["totalWeight"] += weightDiff;
          } else  if (key.includes("label")) {
            let oldWeight = modifyItem["labelWeight"];
            let weight = this.cutFloat(cellNewValue);
            modifyItem["labelWeight"] = weight;
            let weightDiff = weight - oldWeight;
            this.totalWeight += weightDiff;
            modifyItem["totalWeight"] += weightDiff;
          } else {
            modifyItem[key] = cellOldValue;
          }
        }
      }
    },
    created() {
      if (!this.isInit){
        soundInsulationWeightCommand.init(800, 500, 550, () => {
          this.datum.splice(0);
          this.defaultTableHead = Object.keys(this.variableFiledNames);
        });
      }
    },
  }
</script>

<style scoped>
  .wrap {
    font-size: 12px;
  }

  .label-container {
    display: flex;
    justify-content: flex-end;
  }

  .label-style {
    font-size: 12px;
    color: #606266;
    line-height: 45px;
  }
</style>
